package com.lzjt.handler.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzjt.model.AccountInfoModel;
import com.lzjt.model.AccountModel;
import com.lzjt.util.JwtUtils;
import com.lzjt.util.Msg;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        AccountModel model = (AccountModel) authentication.getPrincipal();
        String jwtToken = JwtUtils.getJwtToken(model.getId(), model.getUname(), model.getUtype());

        AccountInfoModel info = new AccountInfoModel();
        info.setRealname(model.getRealname()); // 修改为标准命名
        info.setUtype(model.getUtype().substring("ROLE_".length()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        try {
            response.getWriter().write(new ObjectMapper().writeValueAsString(
                    Msg.success().mess("登陆成功").data("token", jwtToken).data("userInfo", info)
            ));
        } catch (IOException e) {
            // 推荐使用日志框架，例如 SLF4J: private static final Logger log = LoggerFactory.getLogger(...)
            // log.error("登录响应写入失败", e);
            throw e;
        }
    }
}
